package com.xbh.management.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xbh.common.base.BaseEntity;
import com.xbh.common.utils.JwtUtil;
import com.xbh.common.web.core.Result;
import com.xbh.management.annotation.Authorization;
import com.xbh.management.model.ManAttendance;
import com.xbh.management.model.ManDepartment;
import com.xbh.management.model.ManDeptUser;
import com.xbh.management.model.ManUser;
import com.xbh.management.service.AttendanceService;
import com.xbh.management.service.DepartmentService;
import com.xbh.management.service.ManDeptUserService;
import com.xbh.management.service.UserService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @program: management-center
 * @description:
 * @author: 许宝华
 * @create: 2021-08-30 14:51
 */
@RestController
@RequestMapping(path = "/department")
public class DepartmentController {

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private ManDeptUserService manDeptUserService;

    @Autowired
    private AttendanceService attendanceService;

    @Autowired
    private UserService userService;


    @PostMapping("/page")
    public Result page(@RequestBody JSONObject params){
        int pageNum = params.getInteger("pageNum");
        int pageSize = params.getInteger("pageSize");
        ManDepartment cus = params.toJavaObject(ManDepartment.class);
        IPage<ManDepartment> list = departmentService.list(new Page<ManDepartment>(pageNum, pageSize), cus);
        return Result.success(list);
    }

    /**
     * 部门树
     * @param params
     * @return
     */
    @PostMapping("/list")
    public Result DeptList(@RequestBody JSONObject params){
        List<ManDepartment> list = departmentService.queryAllDept();
        return Result.success(list);
    }

    /**
     * 根据部门id删除
     * @param params
     * @return
     */
    @PostMapping("/delete")
    public Result delete(@RequestBody JSONObject params){
        Long departmentId = params.getLong("departmentId");
        int flat = departmentService.delCustomerByid(departmentId);
        if(flat>0){
            return Result.success();
        }
        return Result.failed("删除失败");
    }

    /**
     * 保存部门
     * @param params
     * @return
     */
    @PostMapping("/save")
    public Result save(@RequestBody JSONObject params){
        ManDepartment department = params.toJavaObject(ManDepartment.class);
        department.setCreatePerson("许宝华");
        department.setUpdatePerson("许宝华");
        int flat = departmentService.saveCustomer(department);
        if(flat>0){
            return Result.success();
        }
        return Result.failed("保存失败");
    }

    /**
     *
     * @param params
     * @return
     */
    @PostMapping("/saveDeptRelationUser")
    public Result saveDeptRelationUser(@RequestBody JSONObject params){
        ManDepartment department = params.toJavaObject(ManDepartment.class);
        Long departmentId = params.getLong("parentId");
        Long userId = params.getLong("userId");
        if(ObjectUtil.isEmpty(departmentId)){
            return Result.failed("请输入部门");
        }
        if(ObjectUtil.isEmpty(userId)){
            return Result.failed("请输入用户");
        }
        ManDeptUser manDeptUser = new ManDeptUser();
        manDeptUser.setDepartmentId(departmentId);
        manDeptUser.setUserId(userId);
        manDeptUser.setCreatePerson("许宝华");
        manDeptUser.setUpdatePerson("许宝华");
        boolean save = manDeptUserService.save(manDeptUser);
        if(save){
            return Result.success();
        }
        return Result.failed("保存失败");
    }

    /**
     * 批量删除
     * @param params
     * @return
     */
    @PostMapping("/deleteByIds")
    public Result deleteByIds(@RequestBody JSONObject params){
        String departmentIds = params.getString("departmentIds");
        int flat = departmentService.deleteByCusIds(departmentIds);
        if(flat>0){
            return Result.success();
        }
        return Result.failed("删除失败");
    }

    /**
     * 根据部门id查看当前部门
     * @param params
     * @return
     */
    @PostMapping("/selectCustomerById")
    public Result selectCustomerById(@RequestBody JSONObject params){
        Long departmentId = params.getLong("departmentId");
        ManDepartment manDepartment = departmentService.selectCustomerById(departmentId);
        return Result.success(manDepartment);
    }

    /**
     * 根据部门id修改部门
     * @param params
     * @return
     */
    @PostMapping("/updateCustomer")
    public Result updateCustomer(@RequestBody JSONObject params){
        ManDepartment manDepartment = params.toJavaObject(ManDepartment.class);
        int flat = departmentService.updateCustomerById(manDepartment);
        if(flat>0){
            return Result.success();

        }
        return Result.failed("修改失败");

    }

    /**
     * 导出当前页数据
     * @param params
     * @return
     */
    @PostMapping("/exportCustomer")
    public Result exportCustomer(@RequestBody JSONObject params) throws Exception{
        Integer pageNum = params.getInteger("pageNum");
        Integer pageSize = params.getInteger("pageSize");

        ManDepartment customer = params.toJavaObject(ManDepartment.class);

        //导出当前页数据
        IPage<ManDepartment> list = departmentService.list(new Page<ManDepartment>(pageNum, pageSize), customer);
        List<ManDepartment> records = list.getRecords();
        String downloadURL= departmentService.exportCustomer(records);

        return Result.result("000","获取地址成功",downloadURL);

    }

    /**
     * 导出用户选择的指定客户
     * @param params
     * @return
     * @throws Exception
     */
    @PostMapping("/exportSelectCustomer")
    public Result exportSelectCustomer(@RequestBody JSONObject params) throws Exception {
        String customerIds = params.getString("customerIds");

        List<ManDepartment> customerList = departmentService.selectCustomer(customerIds);

        String downloadURL = departmentService.exportCustomer(customerList);

        return Result.result("000","获取地址成功",downloadURL);

    }

    @PostMapping("/departmentByUser")
    public Result departmentByUser(@RequestBody JSONObject params){
        Long departmentId = params.getLong("departmentId");
        int pageNum = params.getInteger("pageNum");
        int pageSize = params.getInteger("pageSize");
        IPage<ManUser> list = departmentService.selectUserByDepartmentId(new Page<ManUser>(pageNum, pageSize), departmentId);
        return Result.success(list);

    }

    @SneakyThrows
    @PostMapping("/departmentByUserReturnAttendance")
    public Result departmentByUserReturnAttendance(@RequestBody JSONObject params){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Long departmentId = params.getLong("departmentId");

        String year = params.getString("year");
        String start = "-1-1";
        String end = "-12-31";

        String yearStart =year+"-1-1"+" "+"00:00:01";
        String yearEnd = year+"-12-31"+" "+"23:59:59";
        int pageNum = params.getInteger("pageNum");
        int pageSize = params.getInteger("pageSize");
        IPage<ManUser> list = departmentService.selectUserByDepartmentId(new Page<ManUser>(pageNum, pageSize), departmentId);
        if(CollectionUtil.isEmpty(list.getRecords())){
            return Result.failed("当前部门下还没有员工，请移步员工管理进行操作");
        }
        List<Long> userIdList = list.getRecords().stream().map(user -> {
            return user.getUserId();
        }).collect(Collectors.toList());
        LambdaQueryWrapper<ManAttendance> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ManAttendance::getDeleted,0);
        wrapper.in(ManAttendance::getUserId,userIdList);
        wrapper.between(ManAttendance::getCreateTime,simpleDateFormat.parse(yearStart),simpleDateFormat.parse(yearEnd));
        List<ManAttendance> attendanceList = attendanceService.list(wrapper);
        if(CollectionUtil.isEmpty(attendanceList)){
            return Result.failed("此部门在"+year+"年，还没有年度出勤统计");
        }
        Map<Integer, List<ManAttendance>> collect = attendanceList.stream().collect(Collectors.groupingBy(ManAttendance::getAttendanceType));
        JSONObject jsonObject = new JSONObject();
        //未打卡
        if(collect.containsKey(1)){
            jsonObject.put("noPunchCard",collect.get(1).size());
        }
        //已打卡
        if(collect.containsKey(2)){
            jsonObject.put("punchCard",collect.get(2).size());
        }
        //迟到补卡
        if(collect.containsKey(3)){
            jsonObject.put("latePunchCard",collect.get(3).size());
        }
        //请假
        if(collect.containsKey(4)){
            jsonObject.put("leave",collect.get(4).size());
        }


        return Result.success(jsonObject);

    }

    /**
     * 获取当前登录人的直系领导及上级领导
     */

    @PostMapping("/queryUserByDept")
    public Result queryUserByDept(@RequestBody JSONObject params){
        Long userId = JwtUtil.getUserId();
        JSONObject jsonObject = departmentService.queryUserByDept(userId);
        return Result.success(jsonObject);

    }


    /**
     * 查询所有部门
     */

    @PostMapping("/queryAllDept")
    public Result queryAllDept(@RequestBody JSONObject params){
        LambdaQueryWrapper<ManDepartment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ManDepartment::getDeleted,new Integer(0));
        List<ManDepartment> list = departmentService.list(wrapper);
        return Result.success(list);

    }



    /**
     * 部门出勤统计
     */

    @SneakyThrows
    @PostMapping("/queryAllDeptAttendance")
    public Result queryAllDeptAttendance(@RequestBody JSONObject params){
        int pageNum = params.getInteger("pageNum");
        int pageSize = params.getInteger("pageSize");
        String username = params.getString("username");
        JSONArray betweenTime = params.getJSONArray("betweenTime");
        LambdaQueryWrapper<ManDepartment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ManDepartment::getDeleted,new Integer(0));
        List<ManDepartment> list = departmentService.list(wrapper);

        final List<Long>[] userIdList = new List[]{new ArrayList<>()};
        list.stream().forEach( dept ->{
            if(ObjectUtil.isNotEmpty(dept.getUserId())){
                //当前登录人是这个部门领导
                if(dept.getUserId().equals(JwtUtil.getUserId())){
                    //查出该部门下的所有员工
                    LambdaQueryWrapper<ManDeptUser> manDeptUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    manDeptUserLambdaQueryWrapper.eq(ManDeptUser::getDepartmentId,dept.getDepartmentId());
                    List<ManDeptUser> deptUserList = manDeptUserService.list(manDeptUserLambdaQueryWrapper);
                    List<Long> userIdList1 = deptUserList.stream().map(depts -> {
                        return depts.getUserId();
                    }).collect(Collectors.toList());
                    userIdList[0] =userIdList1;
                }
            }

        });

        LambdaQueryWrapper<ManAttendance> attendanceLambdaQueryWrapper = new LambdaQueryWrapper<>();
        attendanceLambdaQueryWrapper.eq(ManAttendance::getDeleted,0);
        attendanceLambdaQueryWrapper.in(ManAttendance::getUserId, userIdList[0]);
        if(StrUtil.isNotEmpty(username)){
            attendanceLambdaQueryWrapper.like(ManAttendance::getUsername,username);
        }
        if(ObjectUtil.isNotEmpty(betweenTime)){

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            attendanceLambdaQueryWrapper.between(ManAttendance::getCreateTime,simpleDateFormat.parse(betweenTime.get(0).toString()),simpleDateFormat.parse(betweenTime.get(1).toString()));
        }
        Page<ManAttendance> page = attendanceService.page(new Page<ManAttendance>(pageNum, pageSize), attendanceLambdaQueryWrapper);
        return Result.success(page);

    }
}
